<template>
  <v-main class="full-height">
    <v-app-bar
        flat
        fixed
        align="center"
        height="60px"
    >
      <v-col cols="2" class="text-left pl-0">
        <v-btn icon @click="$router.back()" class=" justify-start">
          <v-icon color="lighten-1">mdi-arrow-left</v-icon>
        </v-btn>
      </v-col>
      <v-col cols="8">
        <v-card-text>代码生成</v-card-text>
      </v-col>
      <v-col cols="2" class="pr-0 text-right">
      </v-col>
    </v-app-bar>

    <v-container class="mt-15">
      <!--      基本信息-->
      <v-row class="py-0">
        <v-col cols="4" class="py-0">
          <v-card-text>
            命名空间 NameSpace
          </v-card-text>
          <v-text-field dense outlined v-model="nameSpace" style="font-family: Consolas;"></v-text-field>
        </v-col>

        <v-col cols="4" class="py-0">
          <v-card-text >
            命名空间注释
          </v-card-text>
          <v-text-field dense outlined v-model="nameSpaceStr" style="font-family: Consolas;"></v-text-field>
        </v-col>
        <v-col cols="4" class="py-0">
          <v-card-text >
            主键
          </v-card-text>
          <v-text-field dense outlined v-model="sqlId" style="font-family: Consolas;"></v-text-field>
        </v-col>
        <v-col  class="py-0">
          <v-card-text>
            实体字段(fieldName;fieldName;)
          </v-card-text>
          <v-text-field dense outlined v-model="fields" style="font-family: Consolas;"></v-text-field>
        </v-col>
        <v-col cols="auto"  class="py-0 text-right">
          <v-btn class="mt-auto" color="primary" @click="gen">生成</v-btn>
        </v-col>
      </v-row>
      <!--      生成结果部分-->
    </v-container>
    <v-container>
      <v-row>
        <v-col cols="12" class="py-0">
          <v-card-text class="py-0">service</v-card-text>
          <v-textarea outlined v-model="serviceResult" style="font-family: Consolas;">

          </v-textarea>
        </v-col>

        <v-col cols="12" class="py-0">
          <v-card-text class="py-0">serviceImpl</v-card-text>
          <v-textarea outlined v-model="serviceImplResult" style="font-family: Consolas;">

          </v-textarea>
        </v-col>

        <v-col cols="12" class="py-0">
          <v-card-text class="py-0">dao</v-card-text>
          <v-textarea outlined v-model="daoResult" style="font-family: Consolas;">

          </v-textarea>
        </v-col>

        <v-col cols="12" class="py-0">
          <v-card-text class="py-0">daoImpl</v-card-text>
          <v-textarea outlined v-model="daoImplResult" style="font-family: Consolas;">

          </v-textarea>
        </v-col>

        <v-col cols="12" class="py-0">
          <v-card-text class="py-0">mapper</v-card-text>
          <v-textarea outlined v-model="sqlResult" style="font-family: Consolas;">

          </v-textarea>
        </v-col>


      </v-row>
    </v-container>
  </v-main>
</template>

<script>
import {printMsg} from "../util/util";

export default {
  name: "util",
  data: () => ({
    nameSpace:'',
    nameSpaceStr:'',
    sqlId:'',
    fields:'',
    serviceResult:'',
    serviceImplResult:'',
    daoResult:'',
    daoImplResult:'',
    sqlResult:'',

  }),
  methods: {
    gen(){
      this.genService()
      this.genServiceImpl()
      this.genDao()
      this.genDaoImpl()
      this.genMapper()
    },
    genService(){
      this.serviceResult = this.serviceModel.replaceAll("NAME_SPACE",this.nameSpace)
    },
    genServiceImpl(){
      this.serviceImplResult = this.serviceImplModel.replaceAll("NAME_SPACE",this.nameSpace)
    },
    genDao(){
      this.daoResult = this.daoModel.replaceAll("NAME_SPACE",this.nameSpace)
    },
    genDaoImpl(){
      this.daoImplResult = this.daoImplModel.replaceAll("NAME_SPACE",this.nameSpace)
      this.daoImplResult = this.daoImplResult.replaceAll("NAME_STR",this.nameSpaceStr)
    },
    genMapper() {
      this.sqlResult = this.sqlModel
      let namespace = this.nameSpace
      let tableName = this.nameSpace.replace(/([A-Z])/g, "_$1").toLowerCase()
      // helloWorld
      let fields = this.fields.split(";").filter((s) => s)
      // hello_world
      let fieldsLower = fields.map((a) => a.replace(/([A-Z])/g, "_$1").toLowerCase())

      // 替换实体名
      this.sqlResult = this.sqlResult.replaceAll('NAME_SPACE', namespace)
      this.sqlResult = this.sqlResult.replaceAll('TABLE', tableName.substring(tableName.indexOf("_")+1,tableName.length))
      this.sqlResult = this.sqlResult.replaceAll('PRIMARY_KEY', this.sqlId)

      // 处理字段
      let insertFields = fieldsLower.map((a) => `\`${a}\``).join(',\n')
      let insertValues = fields.map((a) => `#{${a}}`).join(',\n')
      this.sqlResult = this.sqlResult.replaceAll('INSERT_FIELDS', insertFields)
      this.sqlResult = this.sqlResult.replaceAll('INSERT_VALUES', insertValues)

      let updateFields = [];
      for (let i = 0; i < fields.length; i++) {
        updateFields.push(`<if test="${fields[i]} != null and ${fields[i]} != ''">
            , t.${fieldsLower[i]} = #{${fields[i]}}
        </if>`)
      }
      this.sqlResult = this.sqlResult.replaceAll('UPDATE_FIELDS', updateFields.join('\n'))

      let listFields = [];
      for (let i = 0; i < fields.length; i++) {
        listFields.push(`t.${fieldsLower[i]},`)
        printMsg(fieldsLower[i], this)
        printMsg(fields[i], this)
        if (fieldsLower[i] !== fields[i]) {
          listFields.push(`t.${fieldsLower[i]} ${fields[i]},`)
        }
      }
      this.sqlResult = this.sqlResult.replaceAll('LIST_FIELDS', listFields.join('\n'))

      let whereFields = []
      for (let i = 0; i < fields.length; i++) {
        whereFields.push(`<if test="${fields[i]} != null and ${fields[i]} != ''">
            and t.${fieldsLower[i]} = #{${fields[i]}}
        </if>`)
      }
      this.sqlResult = this.sqlResult.replaceAll('WHERE_FIELDS', whereFields.join('\n'))
    }


  },

  mounted() {
    this.serviceModel = `NAME_SPACEService
    package com.zyw.zhuangdian.service;

import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.in.NAME_SPACEDtoIn;
import com.zyw.zhuangdian.pojo.out.NAME_SPACEDtoOut;

import java.util.List;

public interface NAME_SPACEService {
    Resp<Void> addNAME_SPACE(NAME_SPACEDtoIn in);
    Resp<Void> updateNAME_SPACE(NAME_SPACEDtoIn in);
    Resp<Void> deleteNAME_SPACE(NAME_SPACEDtoIn in);
    Resp<List<NAME_SPACEDtoOut>> listNAME_SPACEs(NAME_SPACEDtoIn in);
}`
    this.serviceImplModel = `NAME_SPACEServiceImpl
    package com.zyw.zhuangdian.service.impl;

import com.zyw.zhuangdian.constant.ServiceConstant;
import com.zyw.zhuangdian.dao.NAME_SPACEDao;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.dto.PageDto;
import com.zyw.zhuangdian.pojo.in.NAME_SPACEDtoIn;
import com.zyw.zhuangdian.pojo.out.NAME_SPACEDtoOut;
import com.zyw.zhuangdian.service.NAME_SPACEService;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class NAME_SPACEServiceImpl implements NAME_SPACEService {
    private final NAME_SPACEDao NAME_SPACEDao;

    @Override
    public Resp<Void> addNAME_SPACE(NAME_SPACEDtoIn in) {
        Resp<Void> resp = new Resp<>();

        NAME_SPACEDao.addNAME_SPACE(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> updateNAME_SPACE(NAME_SPACEDtoIn in) {
        Resp<Void> resp = new Resp<>();

        NAME_SPACEDao.updateNAME_SPACE(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<Void> deleteNAME_SPACE(NAME_SPACEDtoIn in) {
        Resp<Void> resp = new Resp<>();
        in.setStatus(ServiceConstant.STATUS_INVALID);
        NAME_SPACEDao.updateNAME_SPACE(BeanConvertUtil.beanCovertMap(in));
        return resp;
    }

    @Override
    public Resp<List<NAME_SPACEDtoOut>> listNAME_SPACEs(NAME_SPACEDtoIn in) {
        Resp<List<NAME_SPACEDtoOut>> resp = new Resp<>();
        if (in.getPage() != PageDto.DEFAULT_PAGE){
            if (in.getRow() == PageDto.DEFAULT_PAGE){
                in.setPage(PageDto.DEFAULT_PAGE);
            }else{
                in.setPage((in.getPage() - 1) * in.getRow());
            }
        }
        int count = NAME_SPACEDao.listNAME_SPACEsCount(BeanConvertUtil.beanCovertMap(in));
        if (count > 0){
            List<Map> articles = NAME_SPACEDao.listNAME_SPACE(BeanConvertUtil.beanCovertMap(in));
            List<NAME_SPACEDtoOut> dtoOuts = BeanConvertUtil.covertBeanList(articles,NAME_SPACEDtoOut.class);
            resp.setData(dtoOuts);
        }

        resp.setTotal(count);
        if (in.getPage() != PageDto.DEFAULT_PAGE) {
            resp.setRecords((int) Math.ceil((double) count / (double) in.getRow()));
            resp.setPage(in.getPage());
            resp.setRow(in.getRow());
        }
        return resp;
    }
}`
    this.sqlModel = `NAME_SPACEDaoImplMapper.xml
    <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="NAME_SPACEDaoImpl">
    <insert id="addNAME_SPACE" parameterType="Map">
        insert into TABLE(
            INSERT_FIELDS
        ) values (
            INSERT_VALUES
        )
    </insert>

    <update id="updateNAME_SPACE" parameterType="Map">
        update TABLE t set status = #{status}
        UPDATE_FIELDS
        where t.PRIMARY_KEY = #{PRIMARY_KEY}
    </update>

    <select id="listNAME_SPACEs" parameterType="Map" resultType="Map">
        select t.PRIMARY_KEY,
        LIST_FIELDS
        t.create_time createTime
        from TABLE t
        where t.status = #{status}
        WHERE_FIELDS
        <if test="PRIMARY_KEY != null and PRIMARY_KEY != ''">
            and t.PRIMARY_KEY = #{PRIMARY_KEY}
        </if>
        order by t.create_time desc
        <if test="page != -1 and page != null ">
            limit #{page}, #{row}
        </if>
    </select>
    <select id="listNAME_SPACEsCount" parameterType="Map" resultType="Map">
        select count(1) count
        from TABLE t
        where t.status = #{status}
        WHERE_FIELDS
        <if test="PRIMARY_KEY != null and PRIMARY_KEY != ''">
            and t.PRIMARY_KEY = #{PRIMARY_KEY}
        </if>
    </select>
</mapper>`;
    this.daoImplModel = `NAME_SPACEDaoImpl
    package com.zyw.zhuangdian.dao.impl;

import com.zyw.zhuangdian.dao.BaseDao;
import com.zyw.zhuangdian.dao.NAME_SPACEDao;
import com.zyw.zhuangdian.exceptions.MyDaoException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Repository
@Transactional
public class NAME_SPACEDaoImpl extends BaseDao implements NAME_SPACEDao {
    @Override
    public void addNAME_SPACE(Map in) {
        int i = sqlTemplate.insert("NAME_SPACEDaoImpl.addNAME_SPACE",in);
        if (i<1){
            throw new MyDaoException("插入NAME_STR记录失败");
        }
    }

    @Override
    public void updateNAME_SPACE(Map in) {
        int i = sqlTemplate.update("NAME_SPACEDaoImpl.updateNAME_SPACE",in);
        if (i<1){
            throw new MyDaoException("更新NAME_STR记录失败");
        }
    }

    @Override
    public List<Map> listNAME_SPACE(Map in) {
        List<Map> list = sqlTemplate.selectList("NAME_SPACEDaoImpl.listNAME_SPACEs",in);
        return list;
    }

    @Override
    public int listNAME_SPACEsCount(Map in) {
        List<Map> list = sqlTemplate.selectList("NAME_SPACEDaoImpl.listNAME_SPACEsCount",in);
        if (list.size() < 1){
            return 0;
        }
        return Integer.parseInt(list.get(0).get("count").toString());
    }
}`
    this.daoModel=`NAME_SPACEDao
    package com.zyw.zhuangdian.dao;

import java.util.List;
import java.util.Map;

public interface NAME_SPACEDao {
    void addNAME_SPACE(Map in);
    void updateNAME_SPACE(Map in);
    List<Map> listNAME_SPACE(Map in);
    int listNAME_SPACEsCount(Map in);
}`
  }
}
</script>

<style scoped>

</style>
